package com.example.myapplication.service;

import android.util.Log;
import com.example.myapplication.bean.Response;
import com.example.myapplication.bean.Task;
import com.example.myapplication.util.HttpUtils;
import com.example.myapplication.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class TaskService {
    private static final String URL = "http://101.43.110.183:8080/tasks";
    private static final String TAG = "TaskService";

    public List<Task> getTasks(String name) {
        Map<String, String> params = new HashMap<>();
        if (StringUtils.isEmpty(name)) {
            return Collections.emptyList();
        } else {
            params.put("name", name);
        }
        String responseJson = HttpUtils.get(URL, params);
        Gson gson = new Gson();
        Response<List<Task>> response = gson.fromJson(responseJson, new TypeToken<Response<List<Task>>>() {
        }.getType());
        if (response.getCode() != 200) {
            return Collections.emptyList();
        }
        List<Task> tasks = response.getData();
        Collections.sort(tasks, (t1, t2) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date1 = format.parse(t1.getDates());
                Date date2 = format.parse(t2.getDates());
                return date2.compareTo(date1);
            } catch (ParseException e) {
                Log.e(TAG, "getTasks: Task date format error!", e);
            }
            return 0;
        });
        return tasks;
    }

}
